package cn.ty.znsz.user;


import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import cn.ty.znsz.area.AreaService;
import cn.ty.znsz.common.interceptor.PostInterceptor;
import cn.ty.znsz.role.RoleService;

@Path(value = "/user")
public class UserController extends Controller{
	
	@Inject 
	UserService us;
	@Inject 
	AreaService as;
	@Inject 
	RoleService rs;
	/**
	 * 首页
	 */
	public void index() {
		String cookie=getCookie("jznsz");
		//查询菜单权限
		Ret ret=us.getMenuPoint(getParaToInt("id"),cookie);
		//查询用户所属区划
		Ret ret2=as.getUserArea(cookie);
		setAttr("powers", ret.get("data"));
		setAttr("areas", JsonKit.toJson(ret2.get("data")));
		render("index.html");
	}
	/**
	 * 首页分页
	 */
	public void paginate() {
		Page<Record> page=us.paginate(getParaToInt("pageNumber"), getParaToInt("pageSize"),getPara("loginName"),getPara("startTime"),getPara("endTime"),
				getPara("city"),getPara("county"),getPara("town"),getPara("village"),getPara("status"));
		renderJson(Ret.create().set("msg", "操作成功").set("code", 0).set("count", page.getTotalRow()).set("data", page.getList()));
	}
	/**
	 * 新增用户
	 */
	public void userAdd() {
		//得到该用户所属下角色
		Ret ret=rs.getAllRoles(getCookie("jznsz"));
		//得到该用户下的所有区划
		Ret ret2=as.getAreasById(getCookie("jznsz"));		
		setAttr("roles", ret.get("data"));
		setAttr("areas", JsonKit.toJson(ret2.get("data")));
		render("userAdd.html");
	}
	/**
	 * 保存用户
	 */
	@Before({PostInterceptor.class,UserValidator.class})
	public void userSave() {
		Ret ret=us.userSave(getPara("loginName"),getPara("userName"),getPara("password"),getParaToInt("areaId"),getPara("roleIds"));
		renderJson(ret);
	}
	/**
	 * 判断用户是否有编辑删除重置密码权限
	 */
	public void checkRolePower() {
		Ret ret=us.checkRolePower(getPara("id"),getCookie("jznsz"));
		renderJson(ret);
	}
	/**
	 * 编辑用户
	 */
	public void userEdit() {		
		//得到该用户所属下角色
		Ret ret=rs.getAllRoles(getCookie("jznsz"));
		//得到该用户下的所有区划
		Ret ret2=as.getAreasById(getCookie("jznsz"));		
		setAttr("roles", ret.get("data"));
		setAttr("areas", JsonKit.toJson(ret2.get("data")));
		render("userEdit.html");
	}
	/**
	 * 编辑用户保存
	 */
	@Before({PostInterceptor.class,UserValidator2.class})
	public void userUpdate() {
		Ret ret=us.userUpdate(getPara("userName"),getParaToInt("areaId"),getPara("roleIds"),getParaToInt("id"));
		renderJson(ret);
	}
	/**
	 * 删除用户
	 */
	@Before(PostInterceptor.class)
	public void userDel() {
		Ret ret=us.userUpdate(getParaToInt("id"),getParaToInt("userStatus"));
		renderJson(ret);
	}
	/**
	 * 重置密码
	 */
	@Before(PostInterceptor.class)
	public void userResetPwd() {
		Ret ret=us.userResetPwd(getParaToInt("id"));
		renderJson(ret);
	}
}
